from flask import Flask, jsonify, request
import cv2
import math
import time
import numpy as np

from verify import compare_points, calculate_angle_between_lines

app = Flask(__name__)

qrPoint = [(262, 237), (314, 242), (308, 293), (258, 289)]  # 二维码标准位置
qrLine = (242, 314, 293, 308)  # 二维码标准判断线


# 运行状态常量
class DataManager:
    def __init__(self):
        # 初始化常量
        self.data = ""

    def update_constant(self, new_value):
        # 更新常量的值
        self.data = new_value

    def get_constant(self):
        # 获取常量的值
        return self.data


manager = DataManager()


@app.route('/process_image', methods=['GET'])
def process_image():
    manager.__init__()
    angle_offset_str = "no "
    successful_detection_count = 0  # 用于追踪成功检测的次数

    try:
        for _ in range(3):
            manager.update_constant("正在读取图像")
            cap = cv2.VideoCapture(1)
            # 读取一帧图像
            ret, frame = cap.read()

            timestamp = int(time.time())

            if ret:  # 确保成功读取图像
                cv2.imwrite('frame.jpg', frame)

            detect_obj = cv2.wechat_qrcode_WeChatQRCode('detect.prototxt', 'detect.caffemodel', 'sr.prototxt',
                                                        'sr.caffemodel')

            img = cv2.imread('frame.jpg')
            manager.update_constant("正在确定二维码位置")
            res, points = detect_obj.detectAndDecode(img)

            if points:  # 如果检测到二维码
                array_data = points[0]
                line2 = (array_data[1, 1], array_data[1, 0], array_data[2, 1], array_data[2, 0])
                manager.update_constant("正在计算位置与角度")
                is_position_correct = compare_points(qrPoint, array_data)
                angle = calculate_angle_between_lines(qrLine, line2)
                angle_offset_str = str(angle)

                if angle < 10 and res and is_position_correct:
                    successful_detection_count += 1
                    break  # 检测到二维码后跳出循环

        # 如果在三次检测中至少有一次成功检测到二维码
        if successful_detection_count > 0:
            is_pass = True
        else:
            is_pass = False

        # 构建响应数据
        response_data = {
            'is_pass': is_pass,
            'is_position_correct': is_position_correct,
            'angle_offset': angle_offset_str + 'degrees',
            'info': res
        }

        manager.update_constant("返回结果中")

        return jsonify(response_data)

    except Exception as e:
        return jsonify({'error': str(e)})


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
